/**
 * 博客 API 处理器
 */
import { articles, categories, tags, comments } from '../data/generator.js'

class BlogHandler {
  /**
   * 获取文章列表
   */
  static getArticles(query = {}) {
    // 参数已在中间件中验证，直接使用
    const { page = 1, limit = 10 } = query
    let filteredArticles = [...articles]

    // 多参数状态过滤
    if (query.status) {
      filteredArticles = filteredArticles.filter((article) => query.status.includes(article.status))
    }

    // 多参数分类过滤
    if (query.category) {
      filteredArticles = filteredArticles.filter((article) =>
        query.category.includes(article.category.slug),
      )
    }

    // 多参数标签过滤
    if (query.tag) {
      filteredArticles = filteredArticles.filter((article) =>
        article.tags.some((t) => query.tag.includes(t.slug)),
      )
    }

    // 多参数作者过滤
    if (query.author) {
      filteredArticles = filteredArticles.filter((article) =>
        query.author.includes(article.author.username || article.author),
      )
    }

    // 精选过滤
    if (query.featured !== undefined) {
      const isFeatured = query.featured === 'true' || query.featured === true
      filteredArticles = filteredArticles.filter((article) => article.featured === isFeatured)
    }

    // 日期范围过滤
    if (query.dateRange) {
      const { start, end } = query.dateRange
      if (start && end) {
        const startDate = new Date(start)
        const endDate = new Date(end)
        filteredArticles = filteredArticles.filter((article) => {
          const publishDate = new Date(article.publishDate)
          return publishDate >= startDate && publishDate <= endDate
        })
      }
    }

    // 浏览量范围过滤
    if (query.viewCount) {
      const { min, max } = query.viewCount
      filteredArticles = filteredArticles.filter((article) => {
        if (min !== undefined && article.viewCount < min) return false
        if (max !== undefined && article.viewCount > max) return false
        return true
      })
    }

    // 阅读时间范围过滤
    if (query.readTime) {
      const { min, max } = query.readTime
      filteredArticles = filteredArticles.filter((article) => {
        if (min !== undefined && article.readTime < min) return false
        if (max !== undefined && article.readTime > max) return false
        return true
      })
    }

    // 搜索过滤
    if (query.q) {
      const searchLower = query.q.toLowerCase()
      const searchFields = query.searchFields || ['title', 'content', 'excerpt']

      filteredArticles = filteredArticles.filter((article) => {
        return searchFields.some((field) => {
          if (field === 'title' && article.title.toLowerCase().includes(searchLower)) return true
          if (field === 'content' && article.content.toLowerCase().includes(searchLower))
            return true
          if (field === 'excerpt' && article.excerpt.toLowerCase().includes(searchLower))
            return true
          if (
            field === 'tags' &&
            article.tags.some((tag) => tag.name.toLowerCase().includes(searchLower))
          )
            return true
          return false
        })
      })
    }

    // 多字段排序
    if (query.sort && Array.isArray(query.sort) && query.sort.length > 0) {
      filteredArticles.sort((a, b) => {
        for (const sortItem of query.sort) {
          const { field, order } = sortItem
          let aValue = a[field]
          let bValue = b[field]

          // 处理嵌套字段
          if (field.includes('.')) {
            const fields = field.split('.')
            aValue = fields.reduce((obj, key) => obj?.[key], a)
            bValue = fields.reduce((obj, key) => obj?.[key], b)
          }

          // 处理日期字段
          if (field.includes('Date') || field.includes('Time')) {
            aValue = new Date(aValue).getTime()
            bValue = new Date(bValue).getTime()
          }

          // 比较值
          if (aValue < bValue) return order === 'asc' ? -1 : 1
          if (aValue > bValue) return order === 'asc' ? 1 : -1
        }
        return 0
      })
    } else {
      // 默认排序（按发布时间倒序）
      filteredArticles.sort(
        (a, b) => new Date(b.publishDate).getTime() - new Date(a.publishDate).getTime(),
      )
    }

    // 分页
    const total = filteredArticles.length
    const start = (page - 1) * limit
    const end = start + limit
    const data = filteredArticles.slice(start, end)
    const totalPages = Math.ceil(total / limit)

    return {
      code: 200,
      message: 'success',
      data,
      pagination: {
        page,
        limit,
        total,
        totalPages,
        hasNext: page < totalPages,
        hasPrev: page > 1,
      },
      timestamp: new Date().toISOString(),
    }
  }

  /**
   * 根据 slug 获取文章详情
   */
  static getArticleBySlug(slug) {
    const article = articles.find((item) => item.slug === slug)

    if (!article) {
      return {
        code: 404,
        message: '文章不存在',
        data: null,
      }
    }

    // 增加浏览量
    article.viewCount += 1

    return {
      code: 200,
      message: 'success',
      data: article,
    }
  }

  /**
   * 根据 ID 获取文章详情
   */
  static getArticleById(id) {
    console.log(`🔍 Looking for article with ID: ${id}`)
    console.log(`📊 Total articles: ${articles.length}`)
    console.log(
      `📋 Available IDs: ${articles
        .slice(0, 5)
        .map((a) => a.id)
        .join(', ')}...`,
    )

    const article = articles.find((item) => item.id === id.toString())

    if (!article) {
      console.log(`❌ Article not found with ID: ${id}`)
      return {
        code: 404,
        message: '文章不存在',
        data: null,
      }
    }

    console.log(`✅ Article found: ${article.title}`)
    return {
      code: 200,
      message: 'success',
      data: article,
    }
  }

  /**
   * 获取分类列表
   */
  static getCategories() {
    // 更新分类的文章数量
    const categoriesWithCount = categories.map((category) => ({
      ...category,
      articleCount: articles.filter(
        (article) => article.category.slug === category.slug && article.status === 'published',
      ).length,
    }))

    return {
      code: 200,
      message: 'success',
      data: categoriesWithCount,
    }
  }

  /**
   * 获取标签列表
   */
  static getTags() {
    // 更新标签的文章数量
    const tagsWithCount = tags.map((tag) => ({
      ...tag,
      articleCount: articles.filter(
        (article) =>
          article.tags.some((t) => t.slug === tag.slug) && article.status === 'published',
      ).length,
    }))

    // 按文章数量排序
    tagsWithCount.sort((a, b) => b.articleCount - a.articleCount)

    return {
      code: 200,
      message: 'success',
      data: tagsWithCount,
    }
  }

  /**
   * 搜索文章
   */
  static searchArticles(query = {}) {
    // 参数已在中间件中验证，直接使用
    const { q } = query

    // 使用getArticles方法进行搜索，默认只搜索已发布的文章
    const searchQuery = {
      ...query,
      status: query.status || ['published'], // 确保是数组格式
    }

    const result = this.getArticles(searchQuery)

    // 为搜索结果添加额外信息
    if (result.code === 200) {
      result.query = q
      result.suggestions = this.generateSearchSuggestions(q)
      result.facets = this.generateSearchFacets(result.data)
    }

    return result
  }

  /**
   * 生成搜索建议
   */
  static generateSearchSuggestions(query) {
    const suggestions = []
    const queryLower = query.toLowerCase()

    // 从标题中提取相关建议
    articles.forEach((article) => {
      if (article.status === 'published') {
        const titleWords = article.title.toLowerCase().split(' ')
        titleWords.forEach((word) => {
          if (word.length > 2 && word.includes(queryLower) && !suggestions.includes(word)) {
            suggestions.push(word)
          }
        })
      }
    })

    return suggestions.slice(0, 5)
  }

  /**
   * 生成搜索分面
   */
  static generateSearchFacets(searchResults) {
    const facets = {
      categories: [],
      tags: [],
      authors: [],
    }

    const categoryCount = {}
    const tagCount = {}
    const authorCount = {}

    searchResults.forEach((article) => {
      // 统计分类
      const categorySlug = article.category.slug
      categoryCount[categorySlug] = (categoryCount[categorySlug] || 0) + 1

      // 统计标签
      article.tags.forEach((tag) => {
        tagCount[tag.slug] = (tagCount[tag.slug] || 0) + 1
      })

      // 统计作者
      const authorName = article.author.username || article.author
      authorCount[authorName] = (authorCount[authorName] || 0) + 1
    })

    // 转换为数组格式
    facets.categories = Object.entries(categoryCount).map(([slug, count]) => {
      const category = categories.find((c) => c.slug === slug)
      return { name: category?.name || slug, count }
    })

    facets.tags = Object.entries(tagCount).map(([slug, count]) => {
      const tag = tags.find((t) => t.slug === slug)
      return { name: tag?.name || slug, count }
    })

    facets.authors = Object.entries(authorCount).map(([name, count]) => ({
      name,
      count,
    }))

    return facets
  }

  /**
   * 获取归档数据
   */
  static getArchive() {
    const publishedArticles = articles.filter((article) => article.status === 'published')

    // 按年月分组
    const archiveData = publishedArticles.reduce((acc, article) => {
      const date = new Date(article.publishDate)
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const key = `${year}-${month.toString().padStart(2, '0')}`

      if (!acc[key]) {
        acc[key] = {
          year,
          month,
          articles: [],
        }
      }

      acc[key].articles.push({
        id: article.id,
        title: article.title,
        slug: article.slug,
        publishDate: article.publishDate,
        viewCount: article.viewCount,
      })
      return acc
    }, {})

    // 转换为数组并排序
    const sortedArchive = Object.values(archiveData).sort((a, b) => {
      return b.year - a.year || b.month - a.month
    })

    return {
      code: 200,
      message: 'success',
      data: sortedArchive,
    }
  }

  /**
   * 获取统计信息
   */
  static getStats() {
    const publishedArticles = articles.filter((article) => article.status === 'published')
    const totalViews = publishedArticles.reduce((sum, article) => sum + article.viewCount, 0)
    const featuredCount = publishedArticles.filter((article) => article.featured).length

    return {
      code: 200,
      message: 'success',
      data: {
        totalArticles: publishedArticles.length,
        totalCategories: categories.length,
        totalTags: tags.length,
        totalViews,
        featuredArticles: featuredCount,
        draftArticles: articles.filter((article) => article.status === 'draft').length,
        archivedArticles: articles.filter((article) => article.status === 'archived').length,
      },
    }
  }

  /**
   * 创建文章
   */
  static createArticle(data) {
    const newArticle = {
      id: (Math.max(...articles.map((a) => parseInt(a.id))) + 1).toString(),
      title: data.title || '新文章',
      content: data.content || '',
      excerpt: data.excerpt || '',
      slug: data.slug || `article-${Date.now()}`,
      author: data.author || '匿名',
      publishDate: new Date().toISOString(),
      updateDate: new Date().toISOString(),
      category: data.category || categories[0],
      tags: data.tags || [],
      featured: data.featured || false,
      status: data.status || 'draft',
      readTime: Math.ceil((data.content || '').length / 200) || 1,
      viewCount: 0,
      coverImage: data.coverImage || `https://picsum.photos/800/400?random=${Date.now()}`,
      seoTitle: data.seoTitle || data.title,
      seoDescription: data.seoDescription || data.excerpt,
    }

    articles.push(newArticle)

    return {
      code: 200,
      message: 'success',
      data: newArticle,
    }
  }

  /**
   * 更新文章
   */
  static updateArticle(id, data) {
    const index = articles.findIndex((article) => article.id === id.toString())
    if (index === -1) {
      return {
        code: 404,
        message: '文章不存在',
        data: null,
      }
    }

    articles[index] = {
      ...articles[index],
      ...data,
      id: articles[index].id, // 保持ID不变
      updateDate: new Date().toISOString(),
    }

    return {
      code: 200,
      message: 'success',
      data: articles[index],
    }
  }

  /**
   * 删除文章
   */
  static deleteArticle(id) {
    const index = articles.findIndex((article) => article.id === id.toString())
    if (index === -1) {
      return {
        code: 404,
        message: '文章不存在',
        data: null,
      }
    }

    const deletedArticle = articles.splice(index, 1)[0]

    return {
      code: 200,
      message: 'success',
      data: {
        id: deletedArticle.id,
        title: deletedArticle.title,
      },
    }
  }

  /**
   * 批量更新文章
   */
  static batchUpdateArticles(articleIds, updateData) {
    const updatedArticles = []

    articleIds.forEach((id) => {
      const index = articles.findIndex((article) => article.id === id.toString())
      if (index !== -1) {
        articles[index] = {
          ...articles[index],
          ...updateData,
          updateDate: new Date().toISOString(),
        }
        updatedArticles.push(articles[index])
      }
    })

    return {
      code: 200,
      message: 'success',
      data: updatedArticles,
    }
  }
}

export default BlogHandler
